package com.example.demo.leetcode.classics150;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _93课程表
 * @description
 * @date 2023/08/07 16:55
 * <p>
 * ******************************************************
 */
public class _93课程表 {
    public boolean canFinish1(int numCourses, int[][] prerequisites) {
        // 构建邻接矩阵
        List<Integer>[] graph = new LinkedList[numCourses];
        for (int i = 0; i < numCourses; i++) {
            graph[i] = new LinkedList<>();
        }
        for (int[] prerequisite : prerequisites) {
            int out = prerequisite[0];
            int in = prerequisite[1];
            graph[in].add(out);
        }

        // 计算各个节点的入度
        int[] inDegree = new int[numCourses];
        for (int[] prerequisite : prerequisites) {
            int from = prerequisite[1];
            int to = prerequisite[0];
            inDegree[to]++;
        }

        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] == 0) {
                queue.offer(i);
            }
        }

        int count = 0;
        while (!queue.isEmpty()) {
            Integer curr = queue.poll();
            count++;
            for (Integer integer : graph[curr]) {
                inDegree[integer]--;
                if (inDegree[integer] == 0) {
                    queue.offer(integer);
                }
            }
        }
        return count == numCourses;
    }


    boolean hasCycle = false;
    boolean[] visited;
    boolean[] onPath;

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // 构建邻接矩阵
        List<Integer>[] graph = new LinkedList[numCourses];
        for (int i = 0; i < numCourses; i++) {
            graph[i] = new LinkedList<>();
        }
        for (int[] prerequisite : prerequisites) {
            int out = prerequisite[0];
            int in = prerequisite[1];
            graph[in].add(out);
        }
        visited = new boolean[numCourses];
        onPath = new boolean[numCourses];
        for (int i = 0; i < numCourses; i++) {
            dfs(graph, i);
        }
        return !hasCycle;
    }

    private void dfs(List<Integer>[] graph, int i) {
        if (onPath[i]) {
            // 发现环！！！
            hasCycle = true;
        }

        if (hasCycle || visited[i]) {
            return;
        }

        // 将节点 i 标记为已遍历
        visited[i] = true;
        // 开始遍历节点 s
        onPath[i] = true;

        for (Integer item : graph[i]) {
            dfs(graph, item);
        }
        onPath[i] = false;
    }
}
